<template>

<div class="userListContainer">
    <!-- 搜索框 -->
    <div class="topBox">
			<el-input v-model="keyword" placeholder="用户账号" class="handle-input mr10"></el-input>
			<el-button type="primary" icon="Search" @click="getList(2)">搜索</el-button>
	</div>

    <!-- 头部标题 -->
    <el-table :data="userList" border header-cell-class-name="table-header">
			<el-table-column prop="user_id" label="ID" align="center" min-width="80"></el-table-column>
			<el-table-column prop="username" label="账号" align="center" min-width="100" show-overflow-tooltip></el-table-column>
			<el-table-column prop="nickname" label="昵称" align="center" min-width="100" show-overflow-tooltip></el-table-column>
			<el-table-column label="头像" align="center" min-width="100">
				<template #default="scope">
					<el-image class="face" :src="scope.row.face" fit="cover"/>
				</template>
			</el-table-column>
			<el-table-column label="性别" align="center" min-width="100">
				<template #default="scope">
					{{ scope.row.sex==0?'未知':scope.row.sex==1?'男':'女'}}
				</template>
			</el-table-column>
			<el-table-column label="等级" align="center" min-width="100">
				<template #default="scope">V{{ scope.row.level }}</template>
			</el-table-column>
			<el-table-column label="余额" align="center" min-width="100">
				<template #default="scope">￥{{ scope.row.money }}</template>
			</el-table-column>
			<el-table-column prop="birthday" label="生日" align="center" min-width="120"></el-table-column>
			<el-table-column label="状态" align="center">
				<template #default="scope">
					<el-tag :type="scope.row.status==1?'success':'danger'">
						{{ scope.row.status==1?'正常':'封号'}}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column prop="login_time" label="登录时间" align="center" min-width="170"></el-table-column>
			<el-table-column prop="create_time" label="注册时间" align="center" min-width="120"></el-table-column>
			<el-table-column label="操作" min-width="180" align="center">
				<template #default="scope">
                  <div class="btn">
					<el-button type="primary" icon="Edit" @click="handleEdit(scope.$index, scope.row)" :disabled="isAdmin=='0'">编辑</el-button>
					<el-button icon="Delete" class="red" @click="handleDelete(scope.row.user_id)" :disabled="isAdmin=='0'">删除</el-button>
                  </div>
				</template>
			</el-table-column>
	</el-table>


        <!-- 分页 -->
	   <div class="pagination">
			<el-pagination hide-on-single-page background layout="total, prev, pager, next" :current-page="page" :page-size="row" :total="records" :page-count="total" @current-change="handlePageChange"/>
		</div>
        <!-- 编辑框 -->
       <el-dialog title="编辑" v-model="editVisible" width="380px">
            <el-form label-width="70px">
                <el-form-item label="账号">
                    <el-input v-model="form.name" disabled></el-input>
                </el-form-item>
                <el-form-item label="昵称">
                    <el-input v-model="form.nickname" maxlength="11"></el-input>
                </el-form-item>
				<el-form-item label="余额">
				    <el-input v-model="form.money" maxlength="8" @input="checkMoney"></el-input>
				</el-form-item>
				<el-form-item label="封号" v-if="form.is_admin==0">
				    <el-switch v-model="form.state" active-text="是" inactive-text="否" inline-prompt/>
				</el-form-item>
            </el-form>
            <div class="el-dialog__footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </div>
        </el-dialog>


</div>
</template>

<script setup>
import {ref,reactive, onMounted } from 'vue';
import { ElMessage,ElMessageBox } from 'element-plus';
import { getUserLists,deleteUser,saveUserEdit,checkIsAdmin } from '../../api/manager'
import { userStore } from '../../store/index'
import { decrypt } from '../../core/util';

const uStore = userStore()
const userList = ref([])
let page = ref(1)
let row = ref(10)
let total = ref(1)
let records = ref(1)
const form = ref([])
let editVisible = ref(false)
let keyword = ref('')
let value = ref('')

//获取用户列表数据
const getList = (e) =>{
    //e=2 用来判断是点击搜索框发出的getList请求，而不是初始化获取全部数据的请求。
    if(e==2){
        if(value.value != keyword.value){
            value.value = keyword.value
            page.value = 1
            // list.value = []
        }else{
            return
        }
    }
    const data = {
        page:page.value,
        row:row.value,
        keyword:keyword.value
    }
    getUserLists(data).then(res=>{
        if(res.code == 200){
            userList.value = res.data
            total.value = res.total
            records.value = res.records
        }else{
            ElMessage.error(res.msg)
        }
    })

}

//换页
const handlePageChange = (val) => {
    page.value = val
    getList()
}

//获取用户的管理员身份 0=>普通管理员 1=>超级管理员
// const isAdmin = ref('0')
// const userId = JSON.parse(sessionStorage.getItem('userInfo'))?.user_id || ''
// checkIsAdmin({user_id:userId}).then(res=>{
//     console.log('checkIsAdmin',res)
//     isAdmin.value = res.data
// })
const isAdmin = decrypt(localStorage.getItem('sec'))


//编辑用户
const handleEdit =(index,row) =>{
    
    //需要超级管理员身份
	if(isAdmin == '0'){ return ElMessage.error('您不是超级管理员，没有操作权限！')}
    editVisible.value = true;
    form.value = JSON.parse(JSON.stringify(row))
    form.value.state = form.value.status ==1? false : true
    
    
}

//删除用户
const handleDelete = (user_id) =>{
    //需要超级管理员身份
	if(isAdmin == '0'){ return ElMessage.error('您不是超级管理员，没有操作权限！')}
    ElMessageBox.confirm('确定要删除吗？','提示',{
        confirmButtonText:'确定',
        cancelButtonText:'取消',
        type:'warning',
        buttonSize:'default'
    })
    .then(()=>{
        const data = {user_id:user_id}
        deleteUser(data).then(res=>{
            if(res.code == 200){
                ElMessage.success('删除成功');
                page.value = 1
                getList()
            }else{
                ElMessage.error(res.msg)
            }
        })
    })
    .catch((err)=>ElMessage.error(err))
    
    
}

//验证余额输入框的正则
const checkMoney = () =>{
    var money = form.value.money
    money = money
    .replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
    .replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
    .replace(/^\./g, '')    //保证第一个为数字而不是.
    .replace('.', '$#$')
    .replace(/\./g, '')
    .replace('$#$', '.')
    .replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); // 只能输入两个小数
    if(money.indexOf('.')<0 && money !=''){
        money = parseFloat(money)
    }
    if(money == ''){
        money = 0
    }
    form.value.money = money
}

//保存编辑
const saveEdit = () =>{
    const data = {
        user_id:form.value.user_id,
        nickname:form.value.nickname,
        money:form.value.money,
        status:form.value.state?2:1
    }
    saveUserEdit(data).then(res => {
        if(res.code == 200){
            editVisible.value = false
            ElMessage.success('编辑成功')
            getList()
        }else{
            ElMessage.error(res.msg)
        }
    })
}

//调用获取用户数据
getList();


</script>

<style lang="less" scoped>
.userListContainer{
    .btn{
        display: flex;
        // background-color: #f00;
    }
    .topBox{
        display: flex;
        align-items: center;
        margin: 0 0 15px;
        .el-input{
            width: 200px;
        }
        .el-input__inner{
            border-radius: 3px 0 0 3px;
        }
        .el-button{
            border-radius: 0 3px 3px 0;
        }
	}
    .face {
        width: 40px;
        height: 40px;
    }
    .red{
        color: #f00;
    }
    .el-dialog__footer{
        padding-bottom: 10px;
    }
}
</style>